package com.doudou.casebook;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.doudou.casebook.adapter.AccountAdapter;
import com.doudou.casebook.db.AccountBean;
import com.doudou.casebook.db.DBManager;
import com.doudou.casebook.utils.BudgetDialog;
import com.doudou.casebook.utils.GetTodayTime;
import com.doudou.casebook.utils.MoreDialog;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    ListView todayLv;//展示今日收支记录的ListView
    View headerView;
    TextView topOutTv, topInTv, topBudgetTv, topConTv, lookChartTv;
    ImageView searchIv;
    Button editBtn;
    ImageButton moreBtn;
    ImageView topShowIv;
    List<AccountBean> mDatas;//声明数据源
    AccountAdapter adapter;

    SharedPreferences preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        //添加头布局
        addLVHeaderView();
        preferences = getSharedPreferences("budget", Context.MODE_PRIVATE);
        mDatas = new ArrayList<>();
        //设置适配器:加载每一行数据到列表中
        adapter = new AccountAdapter(this, mDatas);
        todayLv.setAdapter(adapter);

    }

    public void initView() {
        todayLv = findViewById(R.id.main_lv);
        editBtn = findViewById(R.id.main_btn_edit);
        moreBtn = findViewById(R.id.main_btn_more);
        searchIv = findViewById(R.id.main_iv_search);
        editBtn.setOnClickListener(this);
        moreBtn.setOnClickListener(this);
        searchIv.setOnClickListener(this);
        setLVLongClickListener();
    }

    /**
     * 设置ListView长按事件
     */
    private void setLVLongClickListener() {
        todayLv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    return false;
                }
                int pos = position - 1;
                AccountBean clickBean = mDatas.get(pos);
                int Click_id = clickBean.getId();
                //弹出提示用户是否删除对话框
                showDeleteItenDialog(clickBean);
                return false;
            }
        });
    }

    //弹出提示用户是否删除对话框
    private void showDeleteItenDialog(AccountBean accountBean) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_delete_item, null);
        ImageView imageView = dialogView.findViewById(R.id.imageView);
        Glide.with(this)
                .asGif()
                .load(R.drawable.baby_emm)
                .into(imageView);
        builder.setView(dialogView)
                .setTitle("提示信息")
                .setMessage("确定要删除这条记录吗?")
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //执行删除操作
                        DBManager.deleteItemFromAccountById(accountBean.getId());
                        // 移除该对象,刷新
                        mDatas.remove(accountBean);
                        adapter.notifyDataSetChanged();//提示适配器更新数据
                        setTopTvView();//更新顶部提示信息
                    }
                }).create().show();
    }


    //添加头布局
    private void addLVHeaderView() {
//        将布局转换为View对象
        headerView = getLayoutInflater().inflate(R.layout.item_mainlv_top, null);
        todayLv.addHeaderView(headerView);
        //查找头布局可用控件
        topOutTv = headerView.findViewById(R.id.item_mainlv_top_tv_out);
        topInTv = headerView.findViewById(R.id.item_mainlv_tv_in);
        topBudgetTv = headerView.findViewById(R.id.item_mainlv_tv_budget);
        topConTv = headerView.findViewById(R.id.item_mainlv_top_tv_day);
        topShowIv = headerView.findViewById(R.id.item_mainlv_iv_hide);
        lookChartTv = headerView.findViewById(R.id.item_mainlv_top_tv4);
        lookChartTv.setOnClickListener(this);
        topBudgetTv.setOnClickListener(this);
        headerView.setOnClickListener(this);
        topShowIv.setOnClickListener(this);
    }

    //当activity获取焦点时,会调用
    @Override
    protected void onResume() {
        super.onResume();
        loadBDData();
        setTopTvView();
    }

    /**
     * 设置头布局文本内容显示
     */
    private void setTopTvView() {
        // 获取今日收入和支出总金额显示在View中
        float sumMoneyOneDayIn = DBManager.getSumMoneyOneDay(GetTodayTime.year, GetTodayTime.month, GetTodayTime.day, 1);
        float sumMoneyOneDayOut = DBManager.getSumMoneyOneDay(GetTodayTime.year, GetTodayTime.month, GetTodayTime.day, 0);
        String infoOneDay = "今日支出 ¥" + sumMoneyOneDayOut + " 收入 ¥" + sumMoneyOneDayIn;
        topConTv.setText(infoOneDay);
        // 获取本月收入和支出总金额显示在View中
        float sumMoneyOneMonthIn = DBManager.getSumMoneyOneMonth(GetTodayTime.year, GetTodayTime.month, 1);
        float sumMoneyOneMonthOut = DBManager.getSumMoneyOneMonth(GetTodayTime.year, GetTodayTime.month, 0);

        topInTv.setText("¥" + sumMoneyOneMonthIn);
        topOutTv.setText("¥" + sumMoneyOneMonthOut);

        // 设置显示预算剩余
        float bmoney = preferences.getFloat("bmoney", 0);//预算
        if (bmoney == 0) {
            topBudgetTv.setText("¥ 0");

        } else {
            float syMoney = bmoney - sumMoneyOneMonthOut;
            topBudgetTv.setText("¥" + syMoney);

        }


    }

    private void loadBDData() {
        List<AccountBean> list = DBManager.getAccountListOneDayFromAccounttb(GetTodayTime.year, GetTodayTime.month, GetTodayTime.day);
        mDatas.clear();
        mDatas.addAll(list);
        adapter.notifyDataSetChanged();
    }


    /**
     * 头部点击监听事件
     */
    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.main_iv_search) {
            Intent i = new Intent(this, SearchActivity.class);
            startActivity(i);
        } else if (view.getId() == R.id.main_btn_more) {
            MoreDialog moreDialog = new MoreDialog(this);
            moreDialog.show();
            moreDialog.setDialogSize();
        } else if (view.getId() == R.id.main_btn_edit) {
            Intent intent = new Intent(this, RecordActivity.class);
            startActivity(intent);
        } else if (view.getId() == R.id.item_mainlv_tv_budget) {
            showBudgetDialog();
        } else if (view.getId() == R.id.item_mainlv_iv_hide) {
            // 切换TextView明文和密文
            toggleShow();

        } else if (view == lookChartTv) {
            startActivity(new Intent(this, MonthchartActivity.class));
        }

//        if (view == headerView) {
//            //头部点击
//            Toast.makeText(this, "头部点击", Toast.LENGTH_SHORT).show();
//        }
    }

    /**
     * 显示预算设置对话框
     */
    private void showBudgetDialog() {
        BudgetDialog budgetDialog = new BudgetDialog(this);
        budgetDialog.show();
        budgetDialog.setDialogSize();
        budgetDialog.setOnEnsureListener(new BudgetDialog.OnEnsureListener() {
            @Override
            public void onEnsure(float money) {
                //将预算金额写入到共享参数中,进行存储
                SharedPreferences.Editor edit = preferences.edit();
                edit.putFloat("bmoney", money);
                edit.commit();

                //计算剩余金额
                float sumMoneyOneMonth = DBManager.getSumMoneyOneMonth(GetTodayTime.year, GetTodayTime.month, 0);
                float syMoney = money - sumMoneyOneMonth;
                topBudgetTv.setText("¥" + syMoney);
            }
        });
    }

    boolean isShow = true;

    //    切换明文和密文
    private void toggleShow() {
        if (isShow) {//明文
            PasswordTransformationMethod method = PasswordTransformationMethod.getInstance();
            topInTv.setTransformationMethod(method);//设置隐藏
            topOutTv.setTransformationMethod(method);//设置隐藏
            topBudgetTv.setTransformationMethod(method);//设置隐藏
            topShowIv.setImageResource(R.mipmap.ih_hide);
            isShow = false;
        } else {//密文
            HideReturnsTransformationMethod method = HideReturnsTransformationMethod.getInstance();
            topInTv.setTransformationMethod(method);//设置隐显示
            topOutTv.setTransformationMethod(method);//设置隐显示
            topBudgetTv.setTransformationMethod(method);//设置隐显示
            topShowIv.setImageResource(R.mipmap.ih_show);
            isShow = true;
        }
    }
}